package cn.genmer.test.security.polygon;

import com.alibaba.fastjson.JSONObject;
import com.vividsolutions.jts.algorithm.RobustLineIntersector;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.WKTReader;

import java.util.ArrayList;
import java.util.List;

public class PolygonSplitter {
    public static void main(String[] args) {
        String polygonStr = "[[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0], [0.0, 0.0]]";
        String lineStr = "[[2.0, -1.0], [2.0, 5.0]]";

        try {
            GeometryFactory geometryFactory = new GeometryFactory();
            WKTReader reader = new WKTReader(geometryFactory);

            Polygon polygon = (Polygon) reader.read("POLYGON((" + polygonStr.substring(2, polygonStr.length() - 2) + "))");
            LineString line = (LineString) reader.read("LINESTRING(" + lineStr.substring(2, lineStr.length() - 2) + ")");

            Coordinate[] coords = line.getCoordinates();
            RobustLineIntersector lineIntersector = new RobustLineIntersector();
            List<Coordinate> intersectionPoints = new ArrayList<>();

            for (int i = 0; i < polygon.getNumInteriorRing() + 1; i++) {
                LineString ring = i == 0 ? polygon.getExteriorRing() : polygon.getInteriorRingN(i - 1);
                for (int j = 0; j < ring.getNumPoints() - 1; j++) {
                    Coordinate p0 = ring.getCoordinateN(j);
                    Coordinate p1 = ring.getCoordinateN(j + 1);
                    lineIntersector.computeIntersection(p0, p1, coords[0], coords[1]);
                    if (lineIntersector.hasIntersection()) {
                        intersectionPoints.add(lineIntersector.getIntersection(0));
                    }
                }
            }

            if (intersectionPoints.size() == 2) {
                LineString splitLine = geometryFactory.createLineString(intersectionPoints.toArray(new Coordinate[0]));
                Geometry diff = polygon.difference(splitLine);
                JSONObject result = new JSONObject();
                for (int i = 0; i < diff.getNumGeometries(); i++) {
                    result.put("polygon" + (i + 1), diff.getGeometryN(i).toText());
                }
                System.out.println(JSONObject.toJSONString(result));
            } else {
                System.out.println("The line does not intersect the polygon at exactly two points.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
